<template>
  <div class="article-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>公告管理</span>
        </div>
      </template>
      <div class="content-body">
        <!-- 搜索和筛选区域 -->
        <div class="search-filter">
          <el-input 
            v-model="queryForm.title" 
            placeholder="请输入公告标题搜索"
            style="width: 200px; margin-right: 10px;"
            prefix-icon="Search"
            clearable
          />
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleAddArticle">新增公告</el-button>
        </div>
        
        <!-- 文章列表 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="id" label="公告ID" width="80" />
          <el-table-column prop="title" label="公告标题" min-width="300" :show-overflow-tooltip="true" />
          <el-table-column prop="summary" label="公告摘要" min-width="300" :show-overflow-tooltip="true" />
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column prop="status" label="状态" width="120" >
            <template #default="scope">
              <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">{{ scope.row.status === '1' ? '正常' : '已下架' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="是否启用" width="180" >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditArticle(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDeleteNotice(scope.row.id)"
                v-if="!isDeleting"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination 
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑文章弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="800px"
      @close="resetForm"
    >
      <el-form 
        ref="articleFormRef" 
        :model="articleForm" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <!-- 富文本编辑器工具栏 -->
          <!-- 工具栏容器，确保工具栏始终显示 -->
          <div style="border-bottom: 1px solid #ccc; background-color: #fff;">
            <Toolbar
              ref="toolbarRef"
              :editor="editor"
              :defaultConfig="editorConfig"
              :mode="'default'"
            />
          </div>
          <!-- 富文本编辑器内容区 -->
          <Editor
            ref="editorRef"
            :defaultConfig="editorConfig"
            v-model="articleForm.content"
            @onCreated="onEditorCreated"
            mode="default"
            style="height: 400px; border: 1px solid #ccc;width: 680px;"
          />
        </el-form-item>
        <el-form-item label="公告摘要" prop="summary">
          <el-input 
            v-model="articleForm.summary" 
            type="textarea" 
            placeholder="请输入公告摘要（不超过200字）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片上传弹窗 -->
    <el-dialog 
      v-model="imageUploadDialogVisible" 
      title="上传图片" 
      width="500px"
    >
      <el-upload
        class="image-upload"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :on-success="handleImageUploadSuccess"
        :on-error="handleImageUploadError"
        :before-upload="beforeImageUpload"
        :show-file-list="false"
        accept="image/*"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽图片到此处或 <em>点击上传</em>
        </div>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="imageUploadDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, UploadFilled } from '@element-plus/icons-vue'
import { getNoticeList,getNoticeDetail,addOrUpdateNotice,deleteNotice,updateNoticeStatus } from '@/request/article.js'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

// 获取当前项目启动运行时的IP和端口号
const currentServerInfo = ref('')
const fullAddress = ref('')

const getCurrentIPAndPort = () => {
  try {
    // 获取当前页面的主机信息（即项目运行的IP和端口）
    const host = window.location.host
    const protocol = window.location.protocol
    // 显示项目运行信息和连接的后端服务器信息
    // 设置完整地址
    const fullAddressValue = `${protocol}//${host}`
    fullAddress.value = fullAddressValue
    console.log('fullAddress='+fullAddressValue)
  } catch (error) {
    console.error('获取服务器信息失败:', error)
    // 设置默认值，避免后续操作出错
    fullAddress.value = 'http://localhost:8080'
  }
}

getCurrentIPAndPort();
// 上传配置
const uploadUrl = '/api/system/file/uploadFile'
const uploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}

// 图片上传对话框
const imageUploadDialogVisible = ref(false)

// 图片上传相关函数
const handleImageUploadSuccess = (response, file) => {
  console.log('===================================='+response)
  ElMessage.success('图片上传成功')
  imageUploadDialogVisible.value = false
  // 如果需要在编辑器中插入图片，可以在这里处理
}

const handleImageUploadError = (error, file) => {
  console.log('图片上传失败handleImageUploadError')
  ElMessage.error('图片上传失败')
}

const beforeImageUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}



const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  title: '',
  status: ''
})

const isDeleting = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增文章')
const articleFormRef = ref(null)
const editingArticleId = ref(null)
const tableData = ref([])
const total = ref(0)

// 文章表单
const articleForm = reactive({
  title: '',
  content: '',
  summary: '',
  articleType: ''
})

// 编辑器引用
const editor = ref(null)
const editorRef = ref(null)
const toolbarRef = ref(null)

// 编辑器配置
const editorConfig = {
  placeholder: '请输入文章内容...',
  MENU_CONF: {
    uploadImage: {
      server: uploadUrl,
      fieldName: 'file',
      headers: uploadHeaders,
      onSuccess(file, res) {
        console.log('上传成功===========', file, res)
        
        // 针对服务器返回的特定格式：{code: 200, message: '操作成功', data: '图片URL'}
        // 1. 首先检查是否是完整的响应对象
        if (res && res.code === 200) {
          // 如果响应中有code=200，并且data直接是URL
          if (res.data) {
            return res.data; // 直接返回data字段作为图片URL
          }
        }
        
        // 2. 处理可能的其他格式
        if (typeof res === 'string') {
          try {
            const parsedRes = JSON.parse(res);
            if (parsedRes && parsedRes.code === 200 && parsedRes.data) {
              return parsedRes.data;
            }
          } catch (e) {
            console.error('解析响应数据失败:', e);
            // 如果是字符串但不是JSON，可能直接就是URL
            return res;
          }
        }
        
        // 3. 兜底处理
        console.log('未知的响应格式，尝试直接使用res:', res);
        return res;
      },
      // 自定义上传逻辑，完全控制上传过程
      customUpload: async (file, insertFn) => {
        try {
          // 创建FormData对象
          const formData = new FormData();
          formData.append('file', file);
          
          // 发送请求
          const response = await fetch(uploadUrl, {
            method: 'POST',
            headers: uploadHeaders,
            body: formData
          });
          
          // 解析响应
          const data = await response.json();
          console.log('自定义上传响应:', data);
          
          // 检查响应
          if (data.code === 200 && data.data) {
            console.log('上传成功:', data.data);
            // 调用insertFn插入图片
            insertFn(fullAddress.value+'/api'+data.data);
          } else {
            console.error('上传失败:', data.message || '未知错误');
          }
        } catch (error) {
          console.error('上传过程发生错误:', error);
        }
      }
    },
    // 添加视频上传配置
    uploadVideo: {
      server: uploadUrl, // 使用与图片相同的上传地址
      fieldName: 'file',
      headers: uploadHeaders,
      // 视频文件类型限制
      allowedFileTypes: ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/ogg'],
      // 文件大小限制，单位为字节，这里设置为100MB
      maxFileSize: 100 * 1024 * 1024,
      onSuccess(file, res) {
        console.log('视频上传成功:', file, res)
        
        // 处理服务器返回的响应格式，与图片上传相同
        if (res && res.code === 200 && res.data) {
          return res.data;
        }
        
        if (typeof res === 'string') {
          try {
            const parsedRes = JSON.parse(res);
            if (parsedRes && parsedRes.code === 200 && parsedRes.data) {
              return parsedRes.data;
            }
          } catch (e) {
            console.error('解析视频响应数据失败:', e);
            return res;
          }
        }
        
        console.log('未知的视频响应格式，尝试直接使用res:', res);
        return res;
      },
      // 视频自定义上传逻辑
      customUpload: async (file, insertFn) => {
        try {
          // 检查文件类型
          const validTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/ogg'];
          if (!validTypes.includes(file.type)) {
            ElMessage.error('只支持MP4、AVI、MOV、WMV、OGG格式的视频文件');
            return;
          }
          
          // 检查文件大小
          const maxSize = 100 * 1024 * 1024; // 100MB
          if (file.size > maxSize) {
            ElMessage.error('视频文件大小不能超过100MB');
            return;
          }
          
          // 创建FormData对象
          const formData = new FormData();
          formData.append('file', file);
          
          // 发送请求
          const response = await fetch(uploadUrl, {
            method: 'POST',
            headers: uploadHeaders,
            body: formData
          });
          
          // 解析响应
          const data = await response.json();
          console.log('视频自定义上传响应:', data);
          
          // 检查响应
          if (data.code === 200 && data.data) {
            console.log('视频上传成功:', data.data);
            // 调用insertFn插入视频，使用完整的URL路径
            insertFn(fullAddress.value+'/api'+data.data);
          } else {
            console.error('视频上传失败:', data.message || '未知错误');
            ElMessage.error('视频上传失败: ' + (data.message || '未知错误'));
          }
        } catch (error) {
          console.error('视频上传过程发生错误:', error);
          ElMessage.error('视频上传过程中发生错误');
        }
      }
    }
  }
}

// 编辑器创建时的回调
const onEditorCreated = (editorInstance) => {
  editor.value = editorInstance
}

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '文章标题长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 10, message: '文章内容不能少于 10 个字符', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' },
    { min: 10, max: 200, message: '文章摘要长度应在 10 到 200 个字符之间', trigger: 'blur' }
  ],
  articleType: [
    { required: true, message: '请选择文章类型', trigger: 'change' }
  ]
}

// 获取文章列表
const getList=()=>{
  getNoticeList(queryForm.value).then(res=>{
    tableData.value = res.records
    total.value = res.total
  })
}

getList()

// 重置表单
const resetForm = () => {
  if (articleFormRef.value) {
    articleFormRef.value.resetFields()
  }
  editingArticleId.value = null
  Object.keys(articleForm).forEach(key => {
    articleForm[key] = ''
  })
  
  // 清空编辑器内容
  if (editor.value && typeof editor.value.clear === 'function') {
    editor.value.clear()
  }
}

// 新增文章
const handleAddArticle = () => {
  resetForm()
  dialogTitle.value = '新增文章'
  
  // 增加延迟时间确保编辑器能够完全初始化
  setTimeout(() => {
    dialogVisible.value = true
  }, 200)
}

// 编辑文章
const handleEditArticle = (article) => {
  dialogTitle.value = '编辑文章'
  editingArticleId.value = article.id
  getNoticeDetail(article.id).then(res=>{
    // 复制文章数据到表单
    Object.keys(articleForm).forEach(key => {
      articleForm[key] = res[key]
    })
    articleForm.content = articleForm.content.replace('/system/file/',fullAddress.value+'/api/system/file/')
    dialogVisible.value = true
    // 确保编辑器已创建，然后设置内容
      setTimeout(() => {
        nextTick(() => {
          if (editor.value) {
            editor.value.setHtml(articleForm.content)
          }
        })
      }, 100) // 增加小延迟确保对话框和编辑器都已初始化
    })
  
}

// 提交表单
const handleSubmit = () => {
  articleFormRef.value.validate((valid) => {
    if (valid) {
      // 创建提交表单数据的副本
      const submitData = { ...articleForm }
      // 如果有编辑器实例，获取最新的HTML内容
      if (editor.value) {
        submitData.content = editor.value.getHtml()
      } else {
        // 如果编辑器不存在，使用表单中的原始内容
        submitData.content = articleForm.content
      }
       submitData.content = submitData.content.replace(fullAddress.value+'/api', '')
      if (editingArticleId.value) {
        // 编辑模式
        submitData.id = editingArticleId.value
        addOrUpdateNotice(submitData).then(res=>{
          ElMessage.success('公告更新成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('公告更新失败')
        })
      } else {
        // 新增模式
        addOrUpdateNotice(submitData).then(res=>{
          ElMessage.success('公告添加成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('公告添加失败')
        })
      }
    }
  })
}

// 删除文章
const handleDeleteNotice = (id) => {
  ElMessageBox.confirm('确定要删除这篇公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isDeleting.value = true
    deleteNotice(id).then(res=>{
      ElMessage.success('公告删除成功')
      isDeleting.value = false
      getList()
    }).catch(() => {
      ElMessage.error('公告删除失败')
      isDeleting.value = false
    })
  }).catch(() => {
    isDeleting.value = false
  })
}


// 组件卸载时销毁编辑器
onUnmounted(() => {
  if (editor.value) {
    editor.value.destroy()
    editor.value = null
  }
})

// 分页处理
const handleSizeChange = (size) => {
  queryForm.value.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.value.pageNum = current
  getList()
}

const handleStatusChange = (row)=>{
  let msg = row.status=='1'?'下架':'上架'
  ElMessageBox.confirm('确定要'+msg+'这篇公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateNoticeStatus(row.id,row.status=='1'?'1':'0').then(res=>{
      ElMessage.success('公告状态更新成功')
      getList()
    }).catch(() => {
      ElMessage.error('公告状态更新失败')
    })
  }).catch(() => {
    isDeleting.value = false
  })

}
</script>

<style scoped>
.article-management {
  padding: 0px;
}

.search-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 自定义样式 */
.image-upload {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
}

</style>